<template>
   <div class="article-list">
    <van-pull-refresh
      :success-duration="3000"
      success-text="刷新成功"
      v-model="refreshing"
      @refresh="onRefresh"
    >
      <van-list
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        :error.sync="error"
        error-text="请求失败，点击重新加载"
        @load="onLoad"
      >
        <!-- <van-cell
          v-for="(item, index) in list"
          :key="index"
          :title="item.title"
        /> -->
        <article-item v-for="(item, index) in list" :key="index" :item="item" />
      </van-list>
    </van-pull-refresh>
  </div>
</template>

<script>
import ArticleItem from "./article-item";
import { getArticles } from "@/api/article";
export default {
  name: "ArticleList",
  components: {
    ArticleItem,
  },
  //子接收
  props: {
    item: {
      type: Object,
      required: true,
    },
  },
  data() {
    return {
      list: [],
      loading: false, //表示数据是否加载中,默认false
      finished: false, //是否所有数据加载完毕,默认false
      error: false, //用来控制是否出错
      refreshing: false, //记录是否下拉刷新
      timestamp: null, //存下一页数据的起始时间
    };
  },
  methods: {
    async onLoad() {
      try {
        // onLoad中要完成的六件事情;
        //  1. 调接口拿到当前页数据
        const { data } = await getArticles({
          channel_id: this.item.id,
          timestamp: this.timestamp || Date.now(),
          with_top: 1,
        });
        //  2. 把数据放到list的尾部
        this.list.push(...data.results);
        //  3. 把loading设置为false
        this.loading = false;
        //  4. 判断有没有下一页的数据
        //如果返回的pre_timestamp属性为null,代表已经是最后一页
        if (data.pre_timestamp) {
          //  5. 如果有下一页数据，修改分页标识
          //分页参数:让下一次调接口的时候获取时的下一页数据
          this.timestamp = data.pre_timestamp;
        } else {
          //6.如果没有下一页的数据就把finished设置为true
          //表示所有数据加载完成
          this.finished = true;
        }
      } catch (error) {
        this.error = true;
        this.loading = false;
      }
    },
    async onRefresh() {
      // 下拉刷新是要做的几件事情
      // 1. 清空重置数据
      this.loading = true;
      this.list = [];
      this.finished = false;
      this.timestamp = null;

      // 2. 调用onLoad
      await this.onLoad();

      // 3. 把refreshing改回false
      this.refreshing = false;
    },
  },
};
</script>

<style lang="less" scoped>
.article-list {
  margin-top: 88px;
  height: calc(100vh - 188px);
  overflow-y: auto;
}
</style>